package com.novel.service;

import com.novel.commons.SearchContents;
import com.novel.novelSearch.Novel;
import com.search.bturls.Bturls;
import com.search.commons.CommonPage;
import com.search.commons.SearchCore;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by yijy on 2017/7/31.
 */
@Service
public class NovelService {

    public CommonPage<Novel> getBtDataList(String content, Integer currentPage)
    {
        CommonPage<Novel> commonPage = new CommonPage<>();

        commonPage.setCode(SearchContents.CODE_SUCCESS);

        commonPage.setMessage("数据检索成功！");

        List<Novel> list = null;
        try {
            if(currentPage == null)
            {
                currentPage = 1;
            }
            String url = SearchContents.ADDR+SearchContents.Query1 + content + SearchContents.Query2+ currentPage+ SearchContents.Query3 + ".html";

            Document document = SearchCore.getHtmlDom(url);

            if(document != null)
            {
                Element element = document.body();

                Integer count = element.getElementsByClass("result-item result-game-item").size();

                if(count != null && count > 0)
                {
                    list = new ArrayList<>();

                    for(Element item : element.getElementsByClass("result-game-item-detail"))
                    {
                        //获取种子标题
                        Novel novel = addNovels(item);
                        list.add(novel);
                    }

                    Elements pageDatas = element.select("pager-normal-foot");

                    Integer maxPage = 1;
                    //有分页数据
                    if(pageDatas.size() > 0)
                    {
                        for(Element pageItem : pageDatas.first().children())
                        {
                            Matcher mer = Pattern.compile("^[+-]?[0-9]+$").matcher(pageItem.html());
                            if(mer.find())
                            {
                                if(maxPage < Integer.parseInt(pageItem.html()))
                                {
                                    maxPage = Integer.parseInt(pageItem.html());
                                }
                            }
                        }
                        commonPage.setPageCount(maxPage);
                        commonPage.setCurrentCount(currentPage);
                    }else
                    {
                        //无分页数据
                        commonPage.setPageCount(1);
                        commonPage.setCurrentCount(1);
                    }
                }
            }
            commonPage.setDataList(list);
        }catch (Exception e){
             e.printStackTrace();
            commonPage.setCode(SearchContents.CODE_FAIL);
            commonPage.setMessage("数据检索异常！");
        }
        return commonPage;
    }

    private Novel addNovels(Element item){
        if(item==null){
            return null;
        }
        Element elementItemTitle = item.children().first();
        Novel novel = new Novel();

        Element el1 = elementItemTitle.children().first();
        String href = el1.attr("href");
        href = href.substring(href.indexOf("book"));
        href = href.substring(href.indexOf("/")+1);
        //书籍详情路径
        novel.setUrlInfo(href);
        //书名
        novel.setBookname(el1.attr("title"));

        Element  elementDesc = item.children().get(1);
        //书籍简介
        novel.setDesc(elementDesc.html());

        Element  elementBookInfoItem = item.children().get(2);

        Element bookelement = elementBookInfoItem.children().first();
        //作者
        novel.setAuthor(bookelement.children().html());
        Element bookTypeelement;
        //获取最新章节href
        Element newChapter ;
        try {
            bookTypeelement = elementBookInfoItem.children().get(1);
            //书籍类型
            novel.setBookType(bookTypeelement.html());
            //更新时间
            novel.setUpdateTime(elementBookInfoItem.children().get(2).html());
            newChapter = elementBookInfoItem.children().get(3);
            //最新章节
            novel.setNewChapter(newChapter.children().first().html()+newChapter.children().get(1).html());

            String newChapterhref=  newChapter.children().get(1).attr("href");
            newChapterhref = newChapterhref.substring(newChapterhref.indexOf("book"));
            newChapterhref = newChapterhref.substring(newChapterhref.indexOf("/")+1);
            novel.setNewChapterUrl(newChapterhref);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return novel;
    }

    public Map goManget(String url){
        url = SearchContents.biqu+"/"+url;
        Document document = SearchCore.getHtmlDom(url);
        Map contents = new HashMap();
        if(document != null) {
            Element element = document.body();
            if(element==null){
                return contents;
            }
            int con_size = element.getElementsByClass("con_top").size();
            Elements con_top=null;
            String title="";
            if(con_size>0){
                con_top = element.getElementsByClass("con_top");
                for(Element el: con_top){
                    int a = el.children().size();
                    if( a>0 ){
                        for (int i=2;i<a;i++){
                            title =el.children().get(i).html();
                        }
                    }
                }
                int names = element.getElementsByClass("bookname").size();
                if(names>0){
                    Elements bookname = element.getElementsByClass("bookname");
                    for(Element e2 :bookname){
                        title += "-"+e2.children().first().html();
                    }
                }
                contents.put("title",title);
                Element content = element.getElementById("content");
                if(null!=content){
                    contents.put("content",content.html());
                }

                int bottemsize = element.getElementsByClass("bottem2").size();
                if(bottemsize>0){
                    Elements bottem2 = element.getElementsByClass("bottem2");
                    for (Element b1 : bottem2){
                        String lastChapter =  b1.children().first().attr("href");
                        String mulu = b1.children().get(1).attr("href");
                        String nextChapter = b1.children().get(2).attr("href");
                        contents.put("lastChapter",lastChapter);
                        contents.put("mulu",mulu);
                        contents.put("nextChapter",nextChapter);
                    }
                }
            }

        }
        return contents;
    }

    public List<Novel> readAllContents(String url){
        url = SearchContents.biqu+"/"+url;
        try{
            Document document = SearchCore.getHtmlDom(url);
            List<Novel> list= null;
            if(document != null) {
                Element element = document.body();
                if(null==element){
                    return null;
                }
                Element box_con = element.getElementById("box_con");
                Element dlElement=null;
                if(null==box_con){
                    return null;
                }
                dlElement = box_con.tagName("dl");
                if(null!=dlElement){
                    int dd =  dlElement.getElementsByClass("dd").size();
                    if( dd>0 ){
                        for (int i=0;i<dd;i++){
                            Novel novel= new Novel();
                            novel.setNewChapter(dlElement.children().get(i).html());
                            list.add(novel);
                        }
                        return list;
                    }
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return null;
    }


    private class NovelAllContent extends Thread{

        @Override
        public void run() {
            super.run();
        }
    }
}
